package com.xzx.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/9/26 15:00
 */
public class NIOClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("localhost", 9999));
        while (!socketChannel.finishConnect()) {
            // 等待连接
            System.out.println("等待连接");
            Thread.sleep(1000);
        }
        System.out.println(socketChannel.getLocalAddress() + "连接成功");
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        new Thread(() -> {
            while (true) {
                try {
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            int len = socketChannel.read(buffer);
                            if (len > 0) {
                                System.out.println("接收到服务端回复的数据：" + new String(buffer.array(), 0, len));
                            }
                        }
                        iterator.remove();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        String str;
        Scanner scanner = new Scanner(System.in);
        while ((str = scanner.nextLine()) != null) {
            socketChannel.write(ByteBuffer.wrap(str.getBytes()));
        }

    }
}
